<?php
namespace catetree;

class Catetree
{
	//先获取所有的栏目的id和pid
    public function childrenIds($dbname,$cateid,$empty=false){
    	$data=db($dbname)->field('id,pid')->select();
    	return $this->_childrenIds($data,$cateid,$empty);
    }
    //递归获取子栏目id
    private function _childrenIds($data,$cateid,$empty=false){
    	//判断是否清空
    	if($empty){
    		$arr=array();
    	}else{
    		static $arr=array();
    	}
    	foreach($data as $k => $v){
    		if($v['pid'] == $cateid){
    			$arr[]=$v['id'];
    			$this->_childrenIds($data,$v['id']);
    		}
    	}
    	return $arr;
    }

    //传入所有cate信息，返回排序后的cate信息
    public function catetree($cateRes){
    	//获取所有的栏目
    	return $this->sort($cateRes);
    }
    
    //无限级栏目排序（通过递归将栏目排好排序）
    public function sort($cateRes,$pid=0,$level=0){
    	//声明空数组
    	static $arr=array();
    	//循环数据
    	foreach($cateRes as $k => $v){
    		if($v['pid'] == $pid){
    			$v['level']=$level;
    			$arr[]=$v;
    			$this->sort($cateRes,$v['id'],$level+1);
    		}
    	}
    	return $arr;
    }

}